package com.chare.config.Component;

import com.chare.pojo.Menu;
import com.chare.pojo.Role;
import com.chare.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.security.Security;
import java.util.Collection;
import java.util.List;

/**权限控制
 * 根据请求的url来分析所需的角色
 *
 * **/
@Component
public class CustomFirter implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private IMenuService menuService;
   AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //获取请求的url
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
       //获取菜单
      List<Menu> menus= menuService.getMenuByAdminName();

        for(Menu menu:menus)
        {
            if(antPathMatcher.match(menu.getUrl(), String.valueOf(requestUrl)))
            {
                //将角色名字传给str数组
                String [] str=menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                //将数组传给list
                return SecurityConfig.createList(str);
            }
        }
        //路径不匹配 返回登录状态
        return  SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
